package main

import (
	"database/sql"
	"fmt"
	"github.com/go-sql-driver/mysql"
	"log"
)

func main() {
	//open函数仅仅填入参数，不马上建立连接。后面query和exec时建立连接
	db, err := sql.Open("mysql","root:abc123456@tcp(139.224.194.158:3307)/jiqun_biao1")  //登录到数据库school中
	if err != nil {
		fmt.Println("cuowu")
	}
	defer db.Close()  //避免频繁连接断开

	var	id, name string
	rows, err := db.Query("select id, name from student where id = ?", "1")
	if err != nil{  //如果结果为0行，不会返回错误
		if driverErr, ok := err.(*mysql.MySQLError); ok {
			if driverErr.Number == 1045 {  //访问被拒绝
				fmt.Println("访问被拒绝")
			}
		}
	}
	//defer rows.Close()
	for rows.Next() {  //next需要与scan配合完成读取，取第一行也要先next
		err := rows.Scan(&id, &name)
		if err != nil {  //每一次迭代检查错误是必要的
			log.Fatal(err)
		}
		log.Println(id, name)
	}
	err = rows.Err()  //返回迭代过程中出现的错误
	if err != nil {
		log.Fatal(err)
	}


}


